<template>
  <!-- 凭证审核 -->
  <PageContainer>
    <view class="container">
      <Header :title="(isAudit && '凭证审核') || '凭证详情'" />
      <BasicsForm
        @register="formRegister"
        @reset="onSubmit('缴费驳回', '请输入驳回原因，指引会员重新提交', 2)"
        @submit="onSubmit('缴费通过', '请输入审核说明', 1)"
        :show-placeholder-view="false"
        :label-width="120"
        :btn-group-options="
          isAudit
            ? {
                reset: {
                  text: '驳回',
                },
                submit: {
                  text: '审核通过',
                },
              }
            : undefined
        "
      ></BasicsForm>

      <ShowModal
        v-model="modalVisible"
        :title="modalTitle"
        confirm-text="确认"
        @confirm="handleConfirm"
      >
        <template #content>
          <div style="width: 100%">
            <div class="pl-20 pt-10" v-if="params.status === AuditStatusEnum.AUDITED">
              <span>请确认款项已到账后操作</span>
            </div>
            <div class="pa-20">
              <UniEasyinput
                type="textarea"
                :placeholder="modalPlaceholder"
                v-model="params.remark"
              />
            </div>
          </div>
        </template>
      </ShowModal>
    </view>
  </PageContainer>
</template>

<script lang="ts" setup>
  /** 凭证审核 */
  import PageContainer from '@/components/PageContainer/index.vue';
  import Header from '@/components/Header/index.vue';
  import { MemberApplyById, PayFeesReview } from '@/api/admin';
  import { memberServiceList, memberGroupList } from '@/api/member';
  import { navigateBack, onLoad } from '@/router';
  import { ref, unref } from 'vue';
  import BasicsForm from '@/components/Form/BasicsForm.vue';
  import { type FormActionType, type FormSchema, useForm } from '@/components/Form';
  import type { IMemberApplyByIdResult } from '@/api/admin/types';
  import { memberTypeGetList } from '@/api/membership';
  import { localDataMapping } from '@/components/Form/hooks/useForm';
  import { Toast } from '@/utils';
  import { ShareTypeEnum } from '@/enums/shareEnum';
  import { useAppStoreWithOut } from '@/store/modules/app';
  import { onShareAppMessage } from '@dcloudio/uni-app';
  import ShowModal from '@/components/ShowModal/index.vue';
  import UniEasyinput from '@/uni_modules/uni-easyinput/components/uni-easyinput/uni-easyinput.vue';
  import type { MemberTypeGetListItem } from '@/api/membership/types';
  import { AuditStatusEnum } from '@/enums/membershipEnum';
  import type { MemberDuesAudit } from '@/router/types/modules';
import { useAppShare } from '@/hooks/core/useAppShare';

  const { setWxSharePath } = useAppShare()

  const modalVisible = ref(false);
  const modalTitle = ref('缴费通过');
  const modalPlaceholder = ref('');
  const params = ref({
    id: 0,
    status: 0,
    remark: '',
  });
  const isAudit = ref(false);

  const reqData = ref<IMemberApplyByIdResult>();
  const selectOptions = ref<{ [x: string]: MemberTypeGetListItem[] }>();

  const [register, { updateSchema, appendSchemaByField }] = useForm({
    labelAlign: 'left',
    validateTrigger: 'bind',
    schemas: [],
  });

  function formRegister(instance: FormActionType) {
    register(instance);
    getSettingInfo();
  }

  const getSettingInfo = async () => {
    try {
      reqData.value = await MemberApplyById(params.value.id);

      console.log('res--->', reqData.value);
      const fields: FormSchema[] = [
        {
          field: 'memberName',
          label: '会员名称',
          component: 'Input',
          dynamicDisabled: true,
          defaultValue: reqData.value?.memberName,
        },
        {
          field: 'levelName',
          label: '申请职务',
          component: 'Input',
          dynamicDisabled: true,
          defaultValue: reqData.value?.levelName,
        },
        {
          field: 'levelId',
          label: '本期职务',
          component: 'Select',
          dynamicDisabled: true,
          defaultValue: reqData.value?.nowLevelId,
          componentProps: {
            localdata: [],
          },
        },
        {
          field: 'standard',
          label: '缴费标准',
          component: 'Input',
          dynamicDisabled: true,
          defaultValue: `${reqData.value?.money || 0}元/${reqData.value?.allottedTime}月`,
        },
        {
          field: 'payMoney',
          label: '应缴金额（￥）',
          component: 'Input',
          dynamicDisabled: true,
          defaultValue: reqData.value?.payMoney,
        },
        {
          field: 'startTime',
          label: '会籍开始时间',
          component: 'DatePicker',
          required: true,
          dynamicDisabled: true,
          defaultValue: reqData.value?.startTime,
        },
        {
          field: 'endTime',
          label: '会籍结束时间',
          component: 'DatePicker',
          required: true,
          dynamicDisabled: true,
          defaultValue: reqData.value?.endTime,
        },
        {
          field: 'paymentVoucher',
          label: '缴费凭证',
          component: 'UploadImg',
          dynamicDisabled: true,
          defaultValue: reqData.value?.paymentVoucher,
          componentProps: {
            limit: 1
          }
        },
        // {
        //   field: 'show',
        //   label: '负责人、企业对外展示',
        //   component: 'Switch',
        //   dynamicDisabled: true,
        //   defaultValue: reqData.value?.memberOtherSettingsDto?.show === 1,
        // },
        // {
        //   field: 'memberPostId',
        //   label: '授予负责人职务',
        //   component: 'Select',
        //   dynamicDisabled: true,
        //   defaultValue: reqData.value?.memberOtherSettingsDto?.memberPostId,
        //   componentProps: {
        //     localdata: [],
        //   },
        // },
        // {
        //   field: 'currentService',
        //   label: '服务专员',
        //   component: 'Select',
        //   dynamicDisabled: true,
        //   defaultValue: reqData.value?.memberOtherSettingsDto?.currentService,
        //   componentProps: {
        //     localdata: [],
        //   },
        // },
        // {
        //   field: 'groupIdList',
        //   label: '标签分组',
        //   dynamicDisabled: true,
        //   component: 'CheckboxGroup',
        //   defaultValue: reqData.value?.memberOtherSettingsDto?.groupIdList,
        //   componentProps: {
        //     localdata: [],
        //   },
        // },
        // {
        //   field: 'remarks',
        //   label: '备注',
        //   component: 'InputTextArea',
        //   dynamicDisabled: true,
        //   defaultValue: reqData.value?.memberOtherSettingsDto?.remarks,
        // },
      ];

      for (let i = 0; i < fields.length; i++) {
        const item = fields[i];
        appendSchemaByField({
          ...item,
        } as FormSchema);
      }

      const typeDataName = [
        { field: 'levelId', type: 'memberLevel' },
        { field: 'memberPostId', type: 'memberPost' },
      ];
      selectOptions.value = await memberTypeGetList(typeDataName.map((v) => v.type));
      for (let index = 0; index < typeDataName.length; index++) {
        const item = typeDataName[index];
        updateSchema({
          field: item.field,
          isOnChange: true,
          componentProps: {
            localdata: localDataMapping(selectOptions.value[item.type], {
              label: 'name',
              value: 'id',
            }),
          },
        });
      }

      let serviceRes = await memberServiceList();
      updateSchema({
        field: 'currentService',
        componentProps: {
          localdata: localDataMapping(serviceRes, { label: 'userName', value: 'id' }),
        },
      });

      let groupRes = await memberGroupList();
      updateSchema({
        field: 'groupIdList',
        componentProps: {
          localdata: localDataMapping(groupRes.records, { label: 'name', value: 'id' }),
        },
      });
    } catch (error) {
      console.error(error);
    }
  };

  const onSubmit = (title: string, placeholder: string, status: number) => {
    modalTitle.value = title;
    modalPlaceholder.value = placeholder;
    params.value.status = status;
    modalVisible.value = true;
  };

  function handleConfirm() {
    PayFeesReview(unref(params)).then((res) => success(res));
  }

  let pageRefresh: MemberDuesAudit['refresh'];
  const success = async (res: any) => {
    Toast({
      title: '操作成功',
      icon: 'none',
      duration: 1500,
      success: () => {
        pageRefresh?.();
        navigateBack();
      },
    });
  };

  onLoad<'MemberDuesAudit'>((op) => {
    params.value.id = op.id;
    pageRefresh = op.refresh;
    isAudit.value = op.isAudit;
  });

  const { hasShareImgConfig } = useAppStoreWithOut();

  onShareAppMessage(() => {
    const membershipShare = hasShareImgConfig(ShareTypeEnum.membership);
    return {
      path: setWxSharePath({ name: 'updateMembershipInfo' }),
      imageUrl: membershipShare?.iconUrl,
      title: membershipShare?.desc,
    };
  });
</script>

<style lang="scss" scoped>
  $color-primary: #2878ff;
  .container {
    padding-top: 30rpx;
    background-color: #fff;
    .report {
      color: $color-primary;
    }
  }
</style>
